package xyz.lwm.lazycat.utility;

import java.util.stream.Collectors;

import static xyz.lwm.lazycat.utility.StrPool.STR_EMPTY;
import static xyz.lwm.lazycat.utility.StrPool.STR_SLASH;

/**
 * @author lwm
 */
public abstract class PathUtil {

    /**
     * normalize path.
     * <pre>
     * for example:
     * a//b/c\\d.txt -> a/b/c/d.txt
     * /a\\b\c/d.txt -> a/b/c/d.txt
     * </pre>
     *
     * @param path path string
     * @return normalized path
     */
    public static String normalizePath(String path) {
        return It.of(path).filter(StringUtil::isNotBlank)
                .let(s -> s.replaceAll("[\\\\/]+", STR_SLASH))
                .let(s -> StringUtil.split(s, STR_SLASH, STR_EMPTY, STR_EMPTY, String::toString))
                .let(list -> list.stream().filter(StringUtil::isNotBlank).collect(Collectors.toList()))
                .let(strList -> StringUtil.join(strList, STR_SLASH, STR_EMPTY, STR_EMPTY, String::toString))
                .orElse(STR_EMPTY).get();
    }

    /**
     * create pathable.
     *
     * @param url url
     * @return pathable
     */
    public static Pathable of(String url) {
        return SimplePathable.of(url);
    }

    public interface Pathable {

        Pathable append(String path);

    }

    private static class SimplePathable implements Pathable {

        public static SimplePathable of(String url) {
            return new SimplePathable(normalizePath(url));
        }

        private final String url;

        private SimplePathable(String url) {
            this.url = url;
        }

        @Override
        public SimplePathable append(String path) {
            String normalizedPath = normalizePath(path);
            return SimplePathable.of(url + STR_SLASH + normalizedPath);
        }

        @Override
        public String toString() {
            return url;
        }

    }

}
